#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <fcntl.h>
#include <errno.h>


#define MAXLINE 80
#define SERV_PORT 8008


int main(){
    //socket
    int lfd=socket(AF_INET,SOCK_STREAM,0);
    //bind
    struct sockaddr_in servaddr,cliaddr;
    servaddr.sin_family=AF_INET;
    servaddr.sin_port=htons(SERV_PORT);
    servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
    bind(lfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
    
    //listen
    listen(lfd,20);

    //accept
    socklen_t cliaddr_len=sizeof(cliaddr);
    int cfd=accept(lfd,(struct sockaddr*)&cliaddr,&cliaddr_len);
    printf("accept success");

    //缓冲区
    char buf[MAXLINE];
    char str[INET_ADDRSTRLEN];//宏定义常用于指定IP地址缓冲区大小，包括\0

    //输出客户单ip和端口号
    printf("receive from %s at port %d\n",inet_ntop(AF_INET,&cliaddr.sin_addr.s_addr,str,sizeof(str)),ntohs(cliaddr.sin_port));

    while(1){
        //read
        bzero(buf,sizeof(buf));
        
        int n=read(STDIN_FILENO,buf,sizeof(buf));//从标准输入中读取数据
        write(cfd,buf,n);//将buf中数据写入套接字
        n=read(cfd,buf,sizeof(buf));//从套接字cfd中读取数据到buf中
        write(STDOUT_FILENO,buf,sizeof(buf));
    }
    close(lfd);
    close(cfd);
    return 0;
    
}

